<?PHP

function member_create($values){
	
	$values["ip"] = get_real_ip();
	$values["created"] = time();
	if(!$values["signup"])$values["signup"] = time();
	if(!$values["pre_reg"])$values["pre_reg"] = 0;
	if(!$values["migrated"])$values["migrated"] = 0;
	if(!$values["verified"])$values["verified"] = 0;
	$sql = "INSERT INTO pi_account (email,password,username,url,active,ip,created,signup,pre_reg,migrated,invitedby,verified)
						VALUES(':email:',':password:',':username:',':url:',1,':ip:',:created:,:signup:,:pre_reg:,:migrated:,':invitedby:',:verified:)";
	
	$GLOBALS["DB"]->values = $values;
	$uid = $GLOBALS["DB"]->insert($sql);
	
	//ADD PROFILE
	$GLOBALS["DB"]->execute("INSERT INTO pi_profile (uid) VALUES(".$uid.")");
	
	//CONVERT levelups to urls for matching.
	if($values["levelup1"]){
		$values["levelup1"] = $values["invitedby"];
		if($values["levelup2"])
			$values["levelup2"] = $GLOBALS["DB3"]->single("SELECT url FROM profile WHERE id=".$values["levelup2"]);
		if($values["levelup3"])
			$values["levelup3"] = $GLOBALS["DB3"]->single("SELECT url FROM profile WHERE id=".$values["levelup3"]);
		if($values["levelup4"])
			$values["levelup4"] = $GLOBALS["DB3"]->single("SELECT url FROM profile WHERE id=".$values["levelup4"]);
		if($values["levelup5"])
			$values["levelup5"] = $GLOBALS["DB3"]->single("SELECT url FROM profile WHERE id=".$values["levelup5"]);
		$GLOBALS["DB"]->execute("INSERT INTO pi_factor (uid,levelup1,levelup2,levelup3,levelup4,levelup5) VALUES(".$uid.",'".$values["levelup1"]."','".$values["levelup2"]."','".$values["levelup3"]."','".$values["levelup4"]."','".$values["levelup5"]."')");
	}
	else{
		//NO REFERS
		$GLOBALS["DB"]->execute("INSERT INTO pi_factor (uid) VALUES(".$uid.")");
	}
	return $uid;	
	
}
function member_login($uid,$remember=1){
	
	if($remember)
		$time = time()+3600*24*365*10;
	else
		$time = 0;
		
	$user = $GLOBALS["DB2"]->row("SELECT fname,lname,email,com_id,pre_reg,url,migrated,code,terms,password,doc_approve,proof_file,next_factor_update,deals_admin FROM pi_profile as p,pi_account as a WHERE p.uid=a.uid AND a.uid=".$uid);
	
	if(!$user["email"]){
		//BAD REGISTRATION?
		//check profile
		$u = $GLOBALS["DB2"]->single("SELECT uid FROM pi_profile WHERE uid=".$uid);
		if(!$u)
			$GLOBALS["DB2"]->execute("INSERT INTO pi_profile (uid) VALUES(".$uid.")");
		$d = $GLOBALS["DB2"]->single("SELECT uid FROM pi_deals WHERE uid=".$uid);
		if(!$d)
			$GLOBALS["DB2"]->execute("INSERT INTO pi_deals (uid) VALUES(".$uid.")");
		$v = $GLOBALS["DB2"]->single("SELECT uid FROM pi_deals WHERE uid=".$uid);
		if(!$v)
			$GLOBALS["DB2"]->execute("INSERT INTO pi_video (uid) VALUES(".$uid.")");
		$user = $GLOBALS["DB2"]->row("SELECT fname,lname,email,com_id,pre_reg,url,migrated,code,terms,password,doc_approve,proof_file,next_factor_update FROM pi_profile as p,pi_account as a WHERE p.uid=a.uid AND a.uid=".$uid);
	}
	
	setcookie("uid",$uid,$time,"/",".perfectinter.net");
	setcookie("pwd",$user["password"],$time,"/",".perfectinter.net");
	
	$_SESSION["deals_admin"]=$user["deals_admin"];
	
	$_SESSION["uid"] = $uid;
	
	$_SESSION["email"] = $user["email"];
	if($user["com_id"])
		$_SESSION["com_id"] = $user["com_id"];
	if($user["fname"])
		$_SESSION["fname"] = $user["fname"];
	
	$_SESSION["url"] = $user["url"];
	
	if($user["next_factor_update"] < time()){
		member_update_factor($uid);
	}
	
	$f = $GLOBALS["DB2"]->row("SELECT * FROM pi_factor WHERE uid=".$uid);
	
	if($user["pre_reg"])
		$_SESSION["ftype"] = "$";
	else
		$_SESSION["ftype"] = "Deal";
		
	$_SESSION["terms"] = $user["terms"];
	//记录登录日志，记录txt
	$data=date('Y-m-d',time());
	$file ="../log/".$data.".txt";
	$file_handle = fopen($file, "a");
	fwrite($file_handle,"UID:".$_SESSION["uid"]."  USERNAME:".$_SESSION["email"]."  LONGTIME:".date('Y-m-d h:i:s',time())."  \n");
	fclose($file_handle);
}
//PSM登录 或者超级管理员登陆
function member_check_login($username,$password){
	$pwd = preg_replace("/".preg_quote("&#124;")."/","|",html_entity_decode($password));
	$pwd=md5($pwd);
	if($username && $pwd){
		//VALIDATE
		$uid = $GLOBALS["DB2"]->single("SELECT uid FROM pi_account WHERE email='".$username."' AND password='".$pwd."' and (deals_admin=1 or deals_admin=2)");
		if($uid)
		{
			member_login($uid);
			return "2";
		}
		else
		{
			return "1";
		}			
	}
}

function mv_video($vid)
{
	//生成16位随机数
	$quid= uuid();
	$query="select url,filename,targetaddress from videos where vid=$vid";
	$vdate=$GLOBALS["DB"]->result($query);
	
	
	$streamfile =$vdate[0]['filename']."/".$vdate[0]['targetaddress'];
	$newstream = $vdate[0]['filename']."/".$quid.".stream";
	if (!copy($streamfile, $newstream)) {
		echo "failed to copy $file...\n";exit;
	}
	else
	{
		 /* echo "seccuss to copy $ud...\n";exit;  */
		 $uid=$_SESSION['uid'];
		 //锁定状态
		 $GLOBALS["DB"]->update("UPDATE user_video SET vstate=1,targetaddress='$newstream' WHERE vid=$vid and uid='$uid'");
		 
		 $queryTwo="select urladdress,appname from user_video where vid=$vid and uid='$uid'";
	     $u_vdate=$GLOBALS["DB"]->result($queryTwo);
		 //记录随机码
		 $_SESSION['quid']=$newstream;
		 $_SESSION['filename']=$quid.".stream";
		 $_SESSION['appname']=$u_vdate[0]['appname'];
		 $_SESSION['urladdress']=$u_vdate[0]['urladdress'];
		 require './play.php';
	}
	/* $uid=$_SESSION['uid'];
	echo $uid;exit; */
}

//16位随机数
function uuid($id = null) {
	if ($id === null) {  // 为空时生成uniqid
		$id = sprintf('%s%03x', uniqid(), mt_rand(0, 0x0fff));
	} elseif ( !empty($id)) {  // 把字符串格式化为uuid格式
		$uuid = '';
		for ($i = 0, $len = strlen($id); $i < $len; $i++) {
			$ord = ord($id[$i]);
			$ord -= ($ord >= 97 ? 87 : 48);
			$uuid .= dechex($ord);
		}
		$id = $uuid;
	}
	return $id;
}

function implode_field_value($array, $glue = ',') {
	$sql = $comma = '';
	foreach ($array as $k => $v) {
		$sql .= $comma."`$k`='$v'";
		$comma = $glue;
	}
	return $sql;
}

function member_logout($uid){
	setcookie("uid",$uid,time() - 13600,"/",".perfectinter.net");
	setcookie("pwd",$pwd,time() - 13600,"/",".perfectinter.net");
	$_SESSION = array();
	
}

function member_auth($uid=0){
	
	static $cache = array();

		if(empty($uid)){
			$User["uid"]  = $_COOKIE("uid");
			$User["pass"] = preg_replace("/".preg_quote("&#124;")."/","|",html_entity_decode($_COOKIE("pass")));
			$uid = $User["uid"];
		}//if
		else{
			$User["uid"] = $uid;
		}//else

		if(!empty($User["uid"])){

			if(isset($cache[$uid]))
				return $cache[$uid];

			$sql_query="SELECT *
						FROM pi_account
						WHERE id=".$User["uid"];

			$this->clean();
			$get = $GLOBALS["DB"]->row($sql_query);
			if(is_array($get)){
				while(list($key,$val) = each($get)){
					if($key != "id" && $key != "password"){
						$User[$key] = $val;
					}//if
				}//while
			}//if
		}//if

		$cache[$uid] = $User;
		return $User;
}
function member_update_levels($uid,$ref_url){
	include_once(DOC_ROOT."/classes/DB3.class.php");
	$GLOBALS["DB"]->execute("UPDATE pi_account SET invitedby='".$ref_url."' WHERE uid=".$uid);
	$GLOBALS["DB"]->execute("UPDATE pi_factor SET levelup1='".$ref_url."' WHERE uid=".$uid);
	
	//LOCAL UPDATE
		//level2
		$l2_url = $GLOBALS["DB"]->single("SELECT url FROM pi_account WHERE invitedby='".$ref_url."'");
		if(!$l2_url)
			$l2_url = $GLOBALS["DB3"]->single("SELECT url FROM profile WHERE invitedby='".$ref_url."'");
		if($l2_url){
			$GLOBALS["DB"]->execute("UPDATE pi_factor SET levelup2='".$l2_url."' WHERE uid=".$uid);
			$l3_url = $GLOBALS["DB"]->single("SELECT url FROM pi_account WHERE invitedby='".$l2_url."'");
			if(!$l3_url)
				$l3_url = $GLOBALS["DB3"]->single("SELECT url FROM profile WHERE invitedby='".$l2_url."'");
			if($l3_url){
				$GLOBALS["DB"]->execute("UPDATE pi_factor SET levelup3='".$l3_url."' WHERE uid=".$uid);
				$l4_url = $GLOBALS["DB"]->single("SELECT url FROM pi_account WHERE invitedby='".$l3_url."'");
				if(!$l4_url)
					$l4_url = $GLOBALS["DB3"]->single("SELECT url FROM profile WHERE invitedby='".$l3_url."'");
				if($l4_url){
					$GLOBALS["DB"]->execute("UPDATE pi_factor SET levelup4='".$l4_url."' WHERE uid=".$uid);
					$l5_url = $GLOBALS["DB"]->single("SELECT url FROM pi_account WHERE invitedby='".$l4_url."'");
					if(!$l5_url)
						$l5_url = $GLOBALS["DB3"]->single("SELECT url FROM profile WHERE invitedby='".$l4_url."'");
					if($l5_url){
						$GLOBALS["DB"]->execute("UPDATE pi_factor SET levelup5='".$l5_url."' WHERE uid=".$uid);
					}
				}
			}
		}
}
function member_update_factor($uid){
	
	if(!isset($_SESSION["updated"])){
		
		$my_ref = $GLOBALS["DB2"]->single("SELECT url FROM pi_account WHERE uid=".$uid);
				
		$l1_count = 0;
		$l2_count = 0;
		$l3_count = 0;
		$l4_count = 0;
		$l5_count = 0;
		
		$res1 = $GLOBALS["DB2"]->result("SELECT url,migrated FROM pi_account WHERE invitedby='".$my_ref."'");
		foreach($res1 as $r1){
			$res2 = $GLOBALS["DB2"]->result("SELECT url,migrated FROM pi_account WHERE invitedby='".$r1["url"]."'");
			if(!$r1["migrated"]) $l1_count += 1;
			foreach($res2 as $r2){
				$res3 = $GLOBALS["DB2"]->result("SELECT url,migrated FROM pi_account WHERE invitedby='".$r2["url"]."'");
				if(!$r2["migrated"]) $l2_count += 1;
				foreach($res3 as $r3){
					$res4 = $GLOBALS["DB2"]->result("SELECT url,migrated FROM pi_account WHERE invitedby='".$r3["url"]."'");
					if(!$r3["migrated"]) $l3_count += 1;
					foreach($res4 as $r4){
						$res5 = $GLOBALS["DB2"]->result("SELECT url,migrated FROM pi_account WHERE invitedby='".$r4["url"]."'");
						if(!$r4["migrated"]) $l4_count += 1;
						foreach($res5 as $r5){
							if(!$r5["migrated"]) $l5_count += 1;
						}
					}
				}
			}
		}
		//make sure row exists  *to fix temp bug. Can be removed down the road
		$exists = $GLOBALS["DB2"]->single("SELECT uid FROM pi_factor WHERE uid=".$uid);
		if(!$exists)
			$GLOBALS["DB2"]->execute("INSERT INTO pi_factor (uid) VALUES(".$uid.")");
		//end bug fix
		
		$GLOBALS["DB2"]->execute("UPDATE pi_factor SET level1cnt = '".$l1_count."', level2cnt='".$l2_count."', level3cnt='".$l3_count."', level4cnt='".$l4_count."', level5cnt='".$l5_count."' WHERE uid=".$uid);
		$_SESSION["updated"] = 1;
		$next = time() + 86400;
		$GLOBALS["DB2"]->execute("UPDATE pi_account SET next_factor_update=".$next." WHERE uid=".$uid);
		
	}
}

//中英文字符截取
function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
{
	if($code =='UTF-8')
	{
		$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
		preg_match_all($pa, $string, $t_string);
		if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."";
		return join('', array_slice($t_string[0], $start, $sublen));
	}
	else
	{
		$start = $start*2;
		$sublen = $sublen*2;
		$strlen = strlen($string);
		$tmpstr = '';
		for($i=0; $i< $strlen; $i++)
		{
			if($i>=$start && $i< ($start+$sublen))
			{
				if(ord(substr($string, $i, 1))>129)
				{
					$tmpstr.= substr($string, $i, 2);
				}
				else
				{
					$tmpstr.= substr($string, $i, 1);
				}
			}
			if(ord(substr($string, $i, 1))>129) $i++;
		}
		if(strlen($tmpstr)< $strlen ) $tmpstr.= "..";
		return $tmpstr;
	}
}
